import { useEffect, useState, useRef } from 'react';
import { Form, Skeleton } from 'antd';
import { Button, Input, Radio, Select, DatePicker, Row, Col, App } from 'antd';
import loadable from '@loadable/component';
import { useNavigate, useSearchParams } from 'react-router-dom';
import dayjs from 'dayjs';

import { getCategoryList, getWorkList, getRoleList, createMerch, updateMerch, getMerchInfo } from '@/service/api';
import { HOME, MERCH_DETAIL } from '@/config/url';
import styles from './index.module.scss';

const WhereSellEditor = loadable(() => import('./components/WhereSellEditor'), {fallback: <Skeleton active/>});
const WhereSelledEditor = loadable(() => import('./components/WhereSelledEditor'), {fallback: <Skeleton active/>});
const FormTag = loadable(() => import('@/components/FormTag'));
const CommonUploadFiles = loadable(() => import('@/components/CommonUploadFiles'), {fallback: <Skeleton active/>});

export default props => {
    const initState = () => ({
        submitting: false,
        workSubmitting: false,
        roleSubmitting: false,
        imgUploading: false,
        categoryList: [],
        workList: [],
        roleList: [],
        workVisible: false,
        roleVisible: false,
    });
    const [state, setState] = useState(initState);
    const [form] = Form.useForm();
    const navigate = useNavigate();
    const { message } = App.useApp();
    const [searchParams] = useSearchParams();
    const id = searchParams.get('id');



    // 编辑时初始化表单，新建时无用
    const initMerch = async () => {
        if(!id) return form.resetFields();
        const [res, err] = await getMerchInfo({id});
        if(err) return message.error(err.message);

        const data = res?.data || {};
        
        // 处理图片数据
        const imageList = data.goodsImages ? data.goodsImages.split(',').filter(Boolean) : [];
        const images = { images: imageList, mainImage: data.mainGoodsImages };

        const whereSelledData = (data.sellingPlats || []).map(item => ({
            plat: item.plat,
            price: item.price,
            date: item.date
        }));

        // 现有编辑器使用纯URL列表，直接透传
        const whereSellData = Array.isArray(data.sellingAddresses)
            ? data.sellingAddresses.filter(Boolean)
            : (data.sellingAddresses ? [data.sellingAddresses] : []);

        const formData = {
            goodsImages: images,
            goodsName: data.goodsName,
            author: data.author || '',
            seriesNames: Array.isArray(data.seriesList) 
                ? data.seriesList.map(item => item.seriesName).filter(Boolean)
                : [],
            charactarNames: Array.isArray(data.charactarList)
                ? data.charactarList.map(item => item.charactarName).filter(Boolean)
                : [],
            nature: String(data.nature),
            categoryId: data.categoryId,
            publicationYear: data.publicationYear ? dayjs(data.publicationYear) : null,
            sellingAddresses: whereSellData,
            sellingPlats: whereSelledData,
            madeIn: data.madeIn || '',
            introduce: data.introduce || ''
        };
        
        form.setFieldsValue(formData);
    };
    // 获取作品列表
    const getWorkData = async () => {
        const [res, err] = await getWorkList({pageNo: 1, pageSize: 9999});
        const workList = (res?.data?.records||[]).map(item => ({value: item.seriesName, label: item.seriesName}));
        setState(o => ({ ...o, workList}));
    };
    // 获取角色列表
    const getRoleData = async () => {
        const [res, err] = await getRoleList({pageNo: 1, pageSize: 9999});
        const roleList = (res?.data?.records||[]).map(item => ({value: item.charactarName, label: item.charactarName}));
        setState(o => ({ ...o, roleList}));
    };
    // 获取分类列表
    const getCategoryData = async () => {
        const [res, err] = await getCategoryList({pageNo: 1, pageSize: 9999});
        const categoryList = (res?.data?.records||[]).map(item => ({value: item.id, label: item.categoryName}));
        setState(o => ({ ...o, categoryList}));
    };
    // 筛选
    const filterOption = (input, option) => {
        if (!input) return true;
        return option.label.toLowerCase().includes(input.toLowerCase());
    };

    // 返回
    const goBack = () => {
        navigate(-1);
    };

    // 新建角色，新建成功后返回首页
    const onSubmit = async () => {
        message.destroy();
        if (state.submitting) return;
        if (state.imgUploading) {
            message.warning('请等待图片上传完成');
            return;
        }
        
        form.validateFields().then(async values => {
            setState(o => ({ ...o, submitting: true }));
            
            try {
                const goodsImages = values.goodsImages?.images?.join(',') || '';
                const mainGoodsImages = values.goodsImages?.mainImage;
                const sellingPlats = (values.sellingPlats || []).filter(Boolean);
                const sellingAddresses = (values.sellingAddresses || []).filter(Boolean);
                const postData = {
                    goodsName: values.goodsName,
                    goodsImages: goodsImages || '',
                    mainGoodsImages: mainGoodsImages || '',
                    categoryId: values.categoryId || '',
                    introduce: values.introduce || '',
                    nature: values.nature || '',
                    publicationYear: values.publicationYear ? dayjs(values.publicationYear).format('YYYY') : '',
                    // 与表单一致：名称列表
                    seriesNames: values.seriesNames || [],
                    charactarNames: values.charactarNames || [],
                    sellingPlats,
                    sellingAddresses,
                    author: (values.author || '').trim(),
                    madeIn: values.madeIn || '',
                    ...(id ? {id} : {}),
                };

                const api = id ? updateMerch : createMerch;

                const [response, err] = await api(postData);
                if (err) {
                    message.error(err.message);
                    return;
                }
                message.success(`${id ? '更新' : '创建'}成功`);
                navigate(id ? `${MERCH_DETAIL}?id=${id}` : HOME, {replace: true});
            } finally {
                setState(o => ({ ...o, submitting: false }));
            }
        }).catch(e => {
            message.warning(`表单填写完整后重新提交`);
        })
    };

    // 获取基础数据（只在组件挂载时执行一次）
    useEffect(() => {
        getWorkData();
        getRoleData();
        getCategoryData();
    }, []);

    // 根据 id 初始化商品数据（当 id 变化时执行）
    useEffect(() => {
        initMerch();
    }, [id]);

    return (
        <>
            <div className={styles['container']}>
                <Form
                    form={form}
                    layout="horizontal"
                    labelWrap={true}
                    colon={false}
                    labelCol={{span: 4}}
                    wrapperCol={{span: 20}}
                >
                    <h3 className={styles['base']}>谷子信息</h3>
                    <Form.Item
                        name="goodsImages"
                        label="图片"
                        rules={[
                            { 
                                required: true, 
                                validator: (_, value) => {
                                    if (!value || !value.images || value.images.length === 0) {
                                        return Promise.reject(new Error('上传谷子图片'));
                                    }
                                    return Promise.resolve();
                                }
                            }
                        ]}
                        labelCol={{span: 2}}
                        wrapperCol={{span: 22}}
                    >
                        <CommonUploadFiles
                            enableMainImage
                            accept="image/*"
                            onUploadingChange={flag => setState(o => ({ ...o, imgUploading: !!flag }))}
                            buttonText="上传图片"
                        />
                    </Form.Item>
                    <Row gutter={12}>
                        <Col xs={24} sm={24} md={12} lg={12} xl={12} xxl={12}>
                            <Form.Item
                                name="goodsName"
                                label="名称"
                                rules={[{ required: true, message: '输入谷子名称' }]}
                            >
                                <Input placeholder="输入谷子名称" maxLength={64} showCount />
                            </Form.Item>
                        </Col>
                        <Col xs={24} sm={24} md={12} lg={12} xl={12} xxl={12}>
                            <Form.Item
                                name="author"
                                label="作者"
                            >
                                <FormTag placeholder="添加作者" maxLength={64} />
                            </Form.Item>
                        </Col>
                    </Row>
                    
                    <Row gutter={12}>
                        <Col xs={24} sm={24} md={12} lg={12} xl={12} xxl={12}>
                            {/* seriesNames: [string, string] */}
                            <Form.Item
                                name="seriesNames"
                                label="作品"
                                rules={[{ required: true, message: '选择作品名称' }]}
                            >
                                <Select
                                    placeholder="选择作品名"
                                    showSearch
                                    filterOption={filterOption}
                                    options={state.workList || []}
                                    mode="tags"
                                />
                            </Form.Item>
                        </Col>
                        <Col xs={24} sm={24} md={12} lg={12} xl={12} xxl={12}>
                            {/* charactarNames: [string, string] */}
                            <Form.Item
                                name="charactarNames" 
                                label="角色"
                                rules={[{ required: true, message: '选择角色名' }]}
                            >
                                <Select
                                    placeholder="选择角色名"
                                    showSearch
                                    filterOption={filterOption}
                                    options={state.roleList || []}
                                    mode="tags"
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                            
                            
                    <Row gutter={12}>
                        <Col xs={24} sm={24} md={12} lg={12} xl={12} xxl={12}>
                            <Form.Item
                                name="categoryId"
                                label="品类"
                                rules={[{ required: true, message: '选择品类' }]}
                            >
                                <Select
                                    placeholder="选择品类名"
                                    showSearch
                                    filterOption={filterOption}
                                    options={state.categoryList || []}
                                />
                            </Form.Item>
                        </Col>
                        <Col xs={24} sm={24} md={12} lg={12} xl={12} xxl={12}>
                            <Form.Item
                                name="nature"
                                label="性质"
                                rules={[{ required: true, message: '选择性质' }]}
                            >
                                <Radio.Group>
                                    <Radio value="1">官谷</Radio>
                                    <Radio value="2">饭制</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={12}>
                        <Col xs={24} sm={24} md={12} lg={12} xl={12} xxl={12}>
                            <Form.Item
                                name="publicationYear"
                                label="发行年份"
                            >
                                <DatePicker 
                                    picker="year" 
                                    placeholder="选择发行年份" 
                                    style={{ width: '100%' }} 
                                    disabledDate={(current) => current && current.year() > dayjs().year()} 
                                />
                            </Form.Item>
                        </Col>
                        <Col xs={24} sm={24} md={12} lg={12} xl={12} xxl={12}>
                            <Form.Item
                                name="madeIn"
                                label="产国"
                            >
                                <Input placeholder="输入产国" style={{ width: '100%' }} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={12}>
                        <Col xs={24} sm={24} md={12} lg={12} xl={12} xxl={12}>
                            <Form.Item
                                name="sellingAddresses"
                                label="这能买到"
                            >
                                <WhereSellEditor />
                            </Form.Item>
                        </Col>
                        <Col xs={24} sm={24} md={12} lg={12} xl={12} xxl={12}>
                            <Form.Item
                                name="sellingPlats"
                                label="交易历史"
                            >
                                <WhereSelledEditor />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={12}>
                        <Col span={24}>
                            <Form.Item
                                name="introduce"
                                label="详情"
                                labelCol={{ span: 2 }}
                                wrapperCol={{ span: 22 }}
                            >
                                <Input.TextArea
                                    placeholder="输入谷子详情"
                                    autoSize={{ minRows: 6, maxRows: 12 }}
                                />
                            </Form.Item>
                        </Col>
                    </Row>

                    {/* 提交 */}
                    <Form.Item noStyle>
                        <div className={styles['footer']}>
                            <Button onClick={goBack} disabled={state.submitting}>返回</Button>
                            <Button onClick={onSubmit} type="primary" htmlType="submit" loading={state.submitting} disabled={state.submitting || state.imgUploading}>提交</Button>
                        </div>
                    </Form.Item>
                </Form>
            </div>
        </>
    )
}
